package autohotkeyide;

import com.gooddies.exceptions.ErrorMessageException;
import java.awt.Point;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

/**
 * @author sad
 */
public class SelectedRegion {

    private final String imagePath;
    private final Point hotSpot;
    private final File imgFile;
    
    public SelectedRegion(String imagePath, Point hotSpot, File imgFile) {
        this.imagePath = imagePath;
        this.hotSpot = hotSpot;
        this.imgFile = imgFile;
    }

    

    public File getImgFile() {
        return imgFile;
    }

    public String getImage() {
        return imagePath;
    }

    public Point getHotSpot() {
        return hotSpot;
    }


    public File calculateImagePath(){
        return new File(imgFile.getParent(), imagePath);
    }
    
    
    /**
     file - img file
     */
    public static SelectedRegion load(File file) {
        Properties properties = new Properties();
        try {
            try (FileReader reader = new FileReader(file)) {
                properties.load(reader);
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        String imagePath = properties.getProperty("imagePath", null);
        if (imagePath == null) {
            throw new ErrorMessageException("Template config file " + file.getAbsolutePath() + " should have property imagePath");
        }

        File imageFile = new File(file.getParentFile(), imagePath);
        if (!imageFile.exists()) {
            throw new ErrorMessageException("Template config file " + file.getAbsolutePath() + " should have property imagePath");
        }

        Point spot = new Point(Integer.parseInt(properties.getProperty("dx", "0")), Integer.parseInt(properties.getProperty("dy", "0")));
        return new SelectedRegion(imagePath, spot, file);
    }

}
